1. Find Truth
If statements and Do loops rely on Boolean
expressions
to control what they do. Those Boolean expressions are usually shown as a condition placeholder in the statement's syntax:
If condition Then ...
and:
Do While condition ...
A Boolean expression
is simply an item that Visual Basic can determine to be either True or
False. Mostly those expressions are very obvious. The fragment If str = "" Then says "if the variable str is an empty string, then execute the following lines of code." In this case, the equal sign (=)
works as a comparison operator, not an assignment operator. Visual
Basic can use the operator both ways because it understands that the
context of an If statement is different from the standalone statement:
str = ""
That line performs an assignment, not a comparison! This type of dual use is called overloading
. If you hear someone say "operators are overloaded in Visual Basic," they are just stating that = can be used two different ways.
There's something else you need to know about Boolean expressions, though. In Visual Basic, any
nonzero value is considered to be True. I know that's weird, but it's
important because it means the following two fragments are equivalent:
If str = "" Then ...
If Len(str) Then ...
The second form literally says "if the length of str,
then..." which doesn't make any sense unless you know that 0 equals
False and any other value equals True. This second form used to be a
common optimization technique because Visual Basic returns the length of
a string very quickly. These types of optimizations are less popular
today, because the clarity of code is now considered more important than
saving a few processor cycles.
Table 1 lists the Visual Basic operators that are used to perform comparisons that result in Boolean expressions.
Table 1. Visual Basic comparison operators
Operator | Comparison | Operator | Comparison |
---|
= | Equal to | <> | Not equal to |
< | Less than | > | Greater than |
<= | Less than or equal to | >= | Greater than or equal to |
Like | Pattern match (strings) | Is | Exact match (objects) |
Expressions can also be combined to form compound Boolean expressions using the operators listed in Table 2.
Table 2. Visual Basic Boolean operators truth table
exp1 | Operator | exp2 | = Result |
---|
True | And | True | True |
True | Or | False | True |
False | Or | True | True |
— | Not | False | True |
True | Eqv | True | True |
False | Eqv | False | True |
True | Imp | True | True |
False | Imp | True | True |
False | Imp | False | True |
True | XOR | False | True |
False | XOR | True | True |
The most-used Boolean operators are And, Or, and Not.
2. Compare Bits
Computers use binary
numbers internally. That's because they don't have 10 fingers to count
on; they have only 2: on and off, which represent 1 and 0, respectively.
Knowing that helps you understand another use for the operators in Table 2—Boolean
operators can also be used in mathematical operations to change the
individual bits that make up a number, as illustrated by the following
code:
Sub ToBorNotToB( )
Dim b As Byte
b = 93
Debug.Print b, Not b, b Or Not b
' Displays: 93 162 255
End Sub
In the preceding code, Not and Or have a mathematical effect on b. Specifically, Not returns the bits that are 0 (255 - b) and Or combines the bits in b and Not b (93 + 162). These are called bitwise operations and they make more sense if you look at b as a binary number (Figure 1).
Bitwise operations are used to determine if a number contains one or more bit flags
. Bit flags are numeric constants that can be combined in a single number without interfering with each other, as shown in Figure 2.
Figure 2 illustrates that the result of the VarType function can contain both the vbArray flag and any of the other type flags. For instance, vbArray And vbVariantOr operator: indicates an array of variants. You can test if a variable contains an array of variants by combining the type flags with the
Sub TestArrayType( )
Dim arr, vt As VbVarType
arr = Array(1, 2, 3, 4, 5)
vt = VarType(arr)
If vt And (vbArray Or vbVariant) Then _
MsgBox "Variable arr is an array of variants."
End Sub
If the bit pattern of vt and vbArray Or vbVariant match, the expression is True and the message is displayed. That kind of test is sometimes called a bit mask
. Bit masking is also used to extract parts of a variable. For instance, the Excel Color property returns a Long
integer value that contains three byte values indicating the red,
green, and blue components of the color as shown by the following code:
Sub ShowColors( )
Dim i As Integer, rng As Range, rgb As Long
Set rng = Range("ColorTable")
For i = 1 To 56
rng.Offset(i, 0).Interior.ColorIndex = i
rgb = rng.Offset(i, 0).Interior.Color
rng.Offset(i, 1).Value = rgb And &HFF
rng.Offset(i, 2).Value = rgb \ &H100 And &HFF
rng.Offset(i, 3).Value = rgb \ &H10000 And &HFF
Next
End Sub
The expression rgb And &HFF returns any of the bits in the first byte of rgb that are 1. The subsequent expressions use integer division to shift to the next byte, getting the second and third bytes from rgb,
which are then masked. It often helps to see the bits in a variable
when working with bitwise operators, so I wrote the following functions
to convert numbers into strings that represent the bit values:
Function ByteToBin(byt As Byte) As String
Dim i As Integer, bin As String
For i = 0 To 7
If byt And 2 ^ i Then
bin = "1" & bin
Else
bin = "0" & bin
End If
Next
ByteToBin = bin
End Function
Function IntToBin(itg As Integer) As String
Dim i As Integer, bin As String
For i = 0 To 15
If itg And 2 ^ i Then
bin = "1" & bin
Else
bin = "0" & bin
End If
Next
IntToBin = bin
End Function
Function LngToBin(lng As Long) As String
Dim i As Integer, bin As String
' Note that this omits 2 ^ 31 because of overflow.
For i = 0 To 30
If lng And 2 ^ i Then
bin = "1" & bin
Else
bin = "0" & bin
End If
Next
LngToBin = bin
End Function